<template>
  <div class="user-management-page">
    <!-- Header -->
    <AppHeader 
      :current-user="currentUser"
      :courses="[]"
      :video-courses="[]"
      :tasks="[]"
      :show-search="false"
      @login="showLoginModal"
      @register="showRegisterModal"
      @logout="handleLogout"
      @show-battle-power="showBattlePowerModal"
    />

    <!-- Navigation Breadcrumb -->
    <nav class="breadcrumb-nav">
      <div class="breadcrumb-content">
        <div class="breadcrumb">
          <router-link to="/" class="breadcrumb-link">
            <i class="fas fa-home"></i>
            首页
          </router-link>
          <i class="fas fa-chevron-right breadcrumb-separator"></i>
          <span class="breadcrumb-item">用户管理</span>
        </div>
      </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
      <div class="container">
        <div class="page-header">
          <h1>用户管理</h1>
          <p>管理系统中的所有用户账户</p>
        </div>

        <!-- User List -->
        <div class="user-list-container">
          <div class="card">
            <div class="card-header">
              <h2>用户列表</h2>
            </div>
            <div class="card-body">
              <div class="table-responsive">
                <table class="user-table">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>用户名</th>
                      <th>邮箱</th>
                      <th>角色</th>
                      <th>状态</th>
                      <th>注册时间</th>
                      <th>最后登录</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="user in users" :key="user.id" :class="{ 'current-user': user.id === currentUser.id }">
                      <td>{{ user.id }}</td>
                      <td>
                        <div class="user-info">
                          <i class="fas fa-user-circle user-avatar"></i>
                          <span>{{ user.name }}</span>
                          <span v-if="user.id === currentUser.id" class="current-tag">当前用户</span>
                        </div>
                      </td>
                      <td>{{ user.email }}</td>
                      <td>
                        <span class="role-badge" :class="user.role">
                          {{ user.role === 'admin' ? '管理员' : '普通用户' }}
                        </span>
                      </td>
                      <td>
                        <span class="status-badge" :class="user.status">
                          {{ getStatusText(user.status) }}
                        </span>
                      </td>
                      <td>{{ formatDate(user.createdAt) }}</td>
                      <td>{{ user.lastLoginAt ? formatDate(user.lastLoginAt) : '从未登录' }}</td>
                      <td>
                        <div class="action-buttons" v-if="canManageUser(user)">
                          <button 
                            class="btn btn-outline btn-small" 
                            @click="editUser(user)"
                            :disabled="isSystemAdmin(user)"
                          >
                            <i class="fas fa-edit"></i>
                            编辑
                          </button>
                          <button 
                            class="btn btn-danger btn-small" 
                            @click="deleteUser(user)"
                            :disabled="isSystemAdmin(user)"
                          >
                            <i class="fas fa-trash"></i>
                            删除
                          </button>
                        </div>
                        <span v-else>-</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- Edit User Modal -->
    <div class="modal" v-if="showEditModal">
      <div class="modal-content edit-user-modal">
        <div class="modal-header">
          <h3>{{ editingUser.id ? '编辑用户' : '创建用户' }}</h3>
          <button class="modal-close" @click="hideEditModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-group">
              <label for="userName">用户名:</label>
              <input 
                type="text" 
                id="userName"
                v-model="editingUser.name" 
                class="form-control"
                :disabled="isSystemAdmin(editingUser)"
                required
              >
            </div>
            <div class="form-group">
              <label for="userEmail">邮箱:</label>
              <input 
                type="email" 
                id="userEmail"
                v-model="editingUser.email" 
                class="form-control"
                :disabled="isSystemAdmin(editingUser)"
                required
              >
            </div>
            <div class="form-group">
              <label for="userRole">角色:</label>
              <select 
                id="userRole"
                v-model="editingUser.role" 
                class="form-control"
                :disabled="isSystemAdmin(editingUser)"
                required
              >
                <option value="user">普通用户</option>
                <option value="admin">管理员</option>
              </select>
            </div>
            <div class="form-group" v-if="!editingUser.id">
              <label for="userPassword">密码:</label>
              <input 
                type="password" 
                id="userPassword"
                v-model="editingUser.password" 
                class="form-control"
                required
              >
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="hideEditModal">取消</button>
          <button 
            class="btn btn-primary" 
            @click="saveUser"
            :disabled="isSystemAdmin(editingUser)"
          >
            保存
          </button>
        </div>
      </div>
    </div>

    <!-- Login Modal -->
    <LoginModal 
      v-if="showLogin"
      @close="hideLoginModal"
      @login-success="handleLoginSuccess"
      @switch-to-register="showRegisterModal"
    />
    
    <!-- Register Modal -->
    <RegisterModal 
      v-if="showRegister"
      @close="hideRegisterModal"
      @register-success="handleRegisterSuccess"
      @switch-to-login="showLoginModal"
    />
    
    <!-- Battle Power Information Modal -->
    <BattlePowerModal 
      v-if="showBattlePower"
      @close="hideBattlePowerModal"
    />
  </div>
</template>

<script>
import AppHeader from '@/components/AppHeader.vue'
import LoginModal from '@/components/LoginModal.vue'
import RegisterModal from '@/components/RegisterModal.vue'
import BattlePowerModal from '@/components/BattlePowerModal.vue'
import apiService from '@/services/api.js'

export default {
  name: 'UserManagement',
  components: {
    AppHeader,
    LoginModal,
    RegisterModal,
    BattlePowerModal
  },
  data() {
    return {
      users: [],
      currentUser: null,
      showLogin: false,
      showRegister: false,
      showBattlePower: false,
      showEditModal: false,
      editingUser: {
        id: null,
        name: '',
        email: '',
        role: 'user',
        password: ''
      }
    }
  },
  async mounted() {
    await this.checkAuthStatus()
    if (this.currentUser && this.currentUser.role === 'admin') {
      await this.loadUsers()
    } else {
      // 如果不是管理员，重定向到首页
      this.$router.push('/')
    }
  },
  methods: {
    async checkAuthStatus() {
      const savedUser = localStorage.getItem('currentUser')
      const savedToken = localStorage.getItem('auth_token')
      
      if (savedUser && savedToken) {
        try {
          this.currentUser = JSON.parse(savedUser)
        } catch (e) {
          console.error('解析用户信息失败:', e)
        }
      }
    },
    async loadUsers() {
      try {
        this.users = await apiService.getUsers()
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$toast.error('获取用户列表失败')
      }
    },
    showLoginModal() {
      this.showLogin = true
    },
    hideLoginModal() {
      this.showLogin = false
    },
    showRegisterModal() {
      this.showRegister = true
    },
    hideRegisterModal() {
      this.showRegister = false
    },
    showBattlePowerModal() {
      this.showBattlePower = true
    },
    hideBattlePowerModal() {
      this.showBattlePower = false
    },
    handleLoginSuccess(user) {
      this.currentUser = user
      this.hideLoginModal()
      // 重新加载用户数据
      this.loadUsers()
    },
    handleRegisterSuccess(user) {
      this.currentUser = user
      this.hideRegisterModal()
    },
    async handleLogout() {
      try {
        await apiService.logout()
      } catch (error) {
        console.error('注销失败:', error)
      } finally {
        this.currentUser = null
        this.$router.push('/')
      }
    },
    editUser(user) {
      this.editingUser = { ...user, password: '' }
      this.showEditModal = true
    },
    hideEditModal() {
      this.showEditModal = false
      this.editingUser = {
        id: null,
        name: '',
        email: '',
        role: 'user',
        password: ''
      }
    },
    async saveUser() {
      try {
        if (this.editingUser.id) {
          // 更新用户
          const userData = {
            name: this.editingUser.name,
            email: this.editingUser.email,
            role: this.editingUser.role
          }
          
          await apiService.updateUser(this.editingUser.id, userData)
          this.$toast.success('用户信息更新成功')
        } else {
          // 创建用户
          const userData = {
            name: this.editingUser.name,
            email: this.editingUser.email,
            role: this.editingUser.role,
            password: this.editingUser.password
          }
          
          await apiService.createUser(userData)
          this.$toast.success('用户创建成功')
        }
        
        // 保存成功，刷新用户列表
        await this.loadUsers()
        this.hideEditModal()
      } catch (error) {
        console.error('保存用户信息失败:', error)
        this.$toast.error('保存用户信息失败: ' + error.message)
      }
    },
    async deleteUser(user) {
      if (!confirm(`确定要删除用户 "${user.name}" 吗？此操作不可恢复。`)) {
        return
      }
      
      try {
        await apiService.deleteUser(user.id)
        this.$toast.success('用户删除成功')
        // 删除成功，刷新用户列表
        await this.loadUsers()
      } catch (error) {
        console.error('删除用户失败:', error)
        this.$toast.error('删除用户失败: ' + error.message)
      }
    },
    isSystemAdmin(user) {
      return user.name === '系统管理员'
    },
    canManageUser(user) {
      return user.id !== this.currentUser.id && !this.isSystemAdmin(user)
    },
    getStatusText(status) {
      const statusMap = {
        active: '活跃',
        inactive: '未激活',
        suspended: '已暂停'
      }
      return statusMap[status] || status
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
  }
}
</script>

<style scoped>
.user-management-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 2rem 0;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 2rem;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.page-header p {
  font-size: 14px;
  color: #64748b;
}

.user-list-container {
  margin-bottom: 2rem;
}

.card {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.card-header {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid #e2e8f0;
}

.card-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.card-body {
  padding: 0;
}

.table-responsive {
  overflow-x: auto;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th,
.user-table td {
  padding: 1rem 1.5rem;
  text-align: left;
  border-bottom: 1px solid #e2e8f0;
}

.user-table th {
  background-color: #f8fafc;
  font-weight: 600;
  color: #64748b;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.user-table tbody tr:last-child td {
  border-bottom: none;
}

.user-table tbody tr:hover {
  background-color: #f8fafc;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.user-avatar {
  font-size: 20px;
  color: #94a3b8;
}

.current-tag {
  background: #3b82f6;
  color: white;
  font-size: 10px;
  padding: 0.125rem 0.5rem;
  border-radius: 12px;
}

.role-badge {
  font-size: 11px;
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-weight: 500;
}

.role-badge.admin {
  background: #fee2e2;
  color: #dc2626;
}

.role-badge.user {
  background: #dbeafe;
  color: #2563eb;
}

.status-badge {
  font-size: 11px;
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #dcfce7;
  color: #166534;
}

.status-badge.inactive {
  background: #e5e7eb;
  color: #4b5563;
}

.status-badge.suspended {
  background: #fee2e2;
  color: #dc2626;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}

.btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  border: none;
}

.btn-outline {
  background: transparent;
  border: 1px solid #e2e8f0;
  color: #64748b;
}

.btn-outline:hover {
  border-color: #3b82f6;
  color: #3b82f6;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover {
  background: #dc2626;
}

.btn-secondary {
  background: #64748b;
  color: white;
}

.btn-secondary:hover {
  background: #475569;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-small {
  padding: 0.25rem 0.5rem;
  font-size: 11px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  font-size: 12px;
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.form-control {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s ease;
}

.form-control:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-control:disabled {
  background: #f1f5f9;
  cursor: not-allowed;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.edit-user-modal {
  max-width: 500px;
}

.modal-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #64748b;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.modal-close:hover {
  background: #f1f5f9;
}

.modal-body {
  padding: 1.5rem;
}

.modal-footer {
  padding: 1rem 1.5rem;
  border-top: 1px solid #e2e8f0;
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

.breadcrumb-nav {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 0.75rem 0;
}

.breadcrumb-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 2rem;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 12px;
  color: #64748b;
}

.breadcrumb-link {
  color: #3b82f6;
  text-decoration: none;
}

.breadcrumb-link:hover {
  text-decoration: underline;
}

.breadcrumb-separator {
  font-size: 10px;
}

.breadcrumb-item {
  color: #1e293b;
}

@media (max-width: 768px) {
  .container {
    padding: 0 1rem;
  }
  
  .user-table th,
  .user-table td {
    padding: 0.75rem 1rem;
  }
  
  .page-header h1 {
    font-size: 20px;
  }
  
  .card-header {
    padding: 1rem;
  }
}
</style>